//
//  ZLMakeView.m
//  ZLCamera
//
//  Created by 科大 on 2024/4/19.
//

#import "ZLMakeView.h"

@interface ZLMakeView()
/// 白色圆心
@property (nonatomic, strong) UIView *whiteView;
/// 环形进度条
@property (nonatomic, strong) CAShapeLayer *progressLayer;
/// 环形进度条
@property (nonatomic, strong) CAShapeLayer *progressBgLayer;
/// 计时器
@property (nonatomic, copy) dispatch_source_t gcdTimer;
/// 当前时长
@property (nonatomic, assign, readwrite) CGFloat videoCurrentTime;
@end

@implementation ZLMakeView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.videoTotalTime = 10;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(takePicture:)];
        [self addGestureRecognizer:tap];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(recordVideo:)];
        longPress.minimumPressDuration = 0.3;
        [self addGestureRecognizer:longPress];
        [self addSubview:self.whiteView];
        [self.layer addSublayer:self.progressBgLayer];
        [self.layer addSublayer:self.progressLayer];
        [self normaleStyle];
    }
    return self;
}

- (void)normaleStyle {
    self.progressLayer.hidden = YES;
    [UIView animateWithDuration:0.2 animations:^{
        self.whiteView.frame = CGRectMake(8, 8, 64, 64);
        self.whiteView.layer.cornerRadius = self.whiteView.frame.size.width / 2.0;
        self.progressBgLayer.strokeColor = [UIColor whiteColor].CGColor;
        self.progressBgLayer.lineWidth = 1.5;
        self.progressBgLayer.transform = CATransform3DIdentity;
        self.progressLayer.transform = CATransform3DIdentity;
    }];
}

- (void)videoStyle:(void (^)(BOOL finished))completion {
    self.layer.borderWidth = 0;
    self.progressLayer.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        self.whiteView.frame = CGRectMake(20, 20, 40, 40);
        self.whiteView.layer.cornerRadius = self.whiteView.frame.size.width / 2.0;
        self.progressLayer.transform = CATransform3DScale(CATransform3DIdentity, 1.2, 1.2, 1.0);
        self.progressBgLayer.strokeColor = [UIColor colorWithWhite:0 alpha:0.4].CGColor;
        self.progressBgLayer.lineWidth = 5;
        self.progressBgLayer.transform = CATransform3DScale(CATransform3DIdentity, 1.2, 1.2, 1.0);
    } completion:completion];
}

#pragma mark - action
/// 拍照
- (void)takePicture:(UITapGestureRecognizer *)tap {
    if (self.makePhoto) {
        self.makePhoto();
    }
}
/// 长按摄像 小视频
- (void)recordVideo:(UILongPressGestureRecognizer *)longPress {
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan: {
            [self videoStyle:^(BOOL finished) {
                [self beginTimer];
                if (self.makeVideo) {
                    self.makeVideo(0, ZLMakeVideoStatusStart);
                }
            }];
        }
            break;
        case UIGestureRecognizerStateEnded: {
            [self cancelTimer];
            [self normaleStyle];
            self.videoCurrentTime = 0;
            self.progressLayer.strokeEnd = 0;
            if (self.makeVideo) {
                self.makeVideo(self.progressLayer.strokeEnd, ZLMakeVideoStatusEnd);
            }
        }
            break;
        default:
            break;
    }
}

- (void)beginTimer {
    self.videoCurrentTime = 0;
    _gcdTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    NSTimeInterval delayTime = 0.f;
    NSTimeInterval timeInterval = 0.1f;
    dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC));
    dispatch_source_set_timer(_gcdTimer, startDelayTime, timeInterval * NSEC_PER_SEC, 0.1 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_gcdTimer, ^{
        self.videoCurrentTime += timeInterval;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.progressLayer.strokeEnd = self.videoCurrentTime/self.videoTotalTime;
            if (self.makeVideo) {
                self.makeVideo(self.progressLayer.strokeEnd, ZLMakeVideoStatusRecording);
            }
        });
    });
    dispatch_resume(_gcdTimer);
}

- (void)cancelTimer {
    if (self.gcdTimer) {
        dispatch_source_cancel(self.gcdTimer);
    }
}

#pragma mark - init

- (UIView *)whiteView {
    if (_whiteView == nil) {
        _whiteView = [UIView new];
        _whiteView.backgroundColor = [UIColor whiteColor];
    }
    return _whiteView;
}

- (CAShapeLayer *)progressLayer {
    if (_progressLayer == nil) {
        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0) radius:self.frame.size.width/2.0 startAngle:- M_PI_2 endAngle:-M_PI_2 + M_PI * 2 clockwise:YES];
        _progressLayer = [CAShapeLayer layer];
        _progressLayer.frame = self.bounds;
        _progressLayer.fillColor = [UIColor clearColor].CGColor;
        _progressLayer.lineWidth = 5;
        _progressLayer.lineCap = kCALineCapRound;
        _progressLayer.strokeColor = [UIColor colorWithWhite:1 alpha:0.8].CGColor;
        _progressLayer.strokeStart = 0;
        _progressLayer.strokeEnd = 0;
        _progressLayer.path = path.CGPath;
    }
    return _progressLayer;
}

- (CAShapeLayer *)progressBgLayer {
    if (_progressBgLayer == nil) {
        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0) radius:self.frame.size.width/2.0 startAngle:- M_PI_2 endAngle:-M_PI_2 + M_PI * 2 clockwise:YES];
        _progressBgLayer = [CAShapeLayer layer];
        _progressBgLayer.frame = self.bounds;
        _progressBgLayer.fillColor = [UIColor clearColor].CGColor;
        _progressBgLayer.lineWidth = 1.5;
        _progressBgLayer.lineCap = kCALineCapRound;
        _progressBgLayer.strokeColor = [UIColor whiteColor].CGColor;
        _progressBgLayer.strokeStart = 0;
        _progressBgLayer.strokeEnd = 1;
        _progressBgLayer.path = path.CGPath;
    }
    return _progressBgLayer;
}

@end
